package com.vhall.component.service.goods.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Splitter;
import com.vhall.component.dao.goods.GoodsMapper;
import com.vhall.component.dao.goods.LiveGoodsMapper;
import com.vhall.component.dao.room.RoomGoodsMapper;
import com.vhall.component.dao.room.RoomMapper;
import com.vhall.component.entity.goods.GoodsEntity;
import com.vhall.component.entity.goods.LiveGoodsEntity;
import com.vhall.component.entity.goods.goods.*;
import com.vhall.component.entity.goods.vo.GetGoodsInfoRequestVO;
import com.vhall.component.entity.goods.vo.GetGoodsInfoResponseVO;
import com.vhall.component.entity.goods.vo.GuoxinPrdApiBindReqVO;
import com.vhall.component.entity.page.vo.PageVO;
import com.vhall.component.entity.room.dto.RoomsEntityDTO;
import com.vhall.component.entity.room.entity.RoomGoodsEntity;
import com.vhall.component.entity.room.enums.RoomAuditStatusEnum;
import com.vhall.component.entity.room.enums.RoomAuditWhichEnum;
import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.framework.common.utils.CollectionUtils;
import com.vhall.component.plugin.common.constant.RedisKey;
import com.vhall.component.plugin.common.exception.BizErrorCode;
import com.vhall.component.plugin.common.properties.ThirdPartyProperties;
import com.vhall.component.plugin.common.support.Token;
import com.vhall.component.plugin.common.support.TokenThreadLocal;
import com.vhall.component.plugin.common.utils.JsonUtil;
import com.vhall.component.service.goods.GuoxinPrdService;
import com.vhall.component.service.goods.LiveGoodsConsoleService;
import com.vhall.component.service.goods.common.GoodsConstant;
import com.vhall.component.service.goods.event.LiveGoodsListRefreshEvent;
import com.vhall.component.service.room.RoomInnerService;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author guoxin.wang
 * @date 2021-06-10 15:21
 */
@SuppressWarnings({"unchecked", "rawtypes"})
@Slf4j
@Service
public class LiveGoodsConsoleServiceImpl extends ServiceImpl<LiveGoodsMapper, LiveGoodsEntity> implements LiveGoodsConsoleService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private LiveGoodsMapper liveGoodsMapper;

    @Autowired
    private RoomInnerService roomInnerService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    @Setter
    private ApplicationEventPublisher applicationEventPublisher;

    @Autowired
    private RoomMapper roomMapper;
    @Resource
    private GuoxinPrdService guoxinPrdService;
    @Resource
    private ThirdPartyProperties thirdPartyProperties;
    @Resource
    private RoomGoodsMapper roomGoodsMapper;
    /**
     * 是否开启房间审核
     * 1为开启
     * 0为关闭房间审核
     */
    @Value("${project.room.audit:0}")
    private Integer roomAuditWitch;

    @Override
    public GoodsPage<LiveGoodsConsoleBindListRspVO> getBindList(LiveGoodsConsoleBindListReqVO reqVO) {
        reqVO.setDefault();
        GoodsPage<LiveGoodsConsoleBindListRspVO> result;
        // 1、获取房间信息。
        RoomsEntityDTO roomInfo = roomInnerService.getRoomInfo(reqVO.getRoomId());
        if (roomInfo == null) {
            throw new BusinessException(BizErrorCode.EMPTY_ROOM);
        }

        // 3、查询其余字段。
        // 先查询缓存。
        if (reqVO.getPage() == 1 && StringUtils.isBlank(reqVO.getKeyword()) && reqVO.getPageSize() == 10) {
            result = getFirstPageGoodsCache(roomInfo.getIlId());
            if (result != null) {
                return result;
            }
        }
        // 再查询数据库。
        Page<LiveGoodsConsoleBindListRspVO> page = new Page<>(reqVO.getPage(), reqVO.getPageSize());
        Map<String, Object> param = new HashMap<>(4);
        param.put("goodsStatus", GoodsConstant.GOODS_STATUS_ON);
        param.put("keyword", StringUtils.isBlank(reqVO.getKeyword()) ? "" : reqVO.getKeyword().trim());
        param.put("ilId", roomInfo.getIlId());
        page = liveGoodsMapper.getBindList(page, param);
        // 3.5、设置结果的goodsSwitchFlag字段。
        List<LiveGoodsConsoleBindListRspVO> records = page.getRecords();
        if (CollectionUtils.isNotEmpty(records)) {
            for (LiveGoodsConsoleBindListRspVO single : records) {
                single.setRoomId(reqVO.getRoomId());
            }
        }
        // 2、获取观众端商品入口开关状态。
        Integer goodsSwitchFlag = getGoodsSwitchCache(reqVO.getRoomId(), records.size() > 0 ? 1 : 0);
        result = new GoodsPage<>(reqVO.getPage(), reqVO.getPageSize(), (int) page.getTotal(), records, goodsSwitchFlag);
        // 4、如果是第一页的话,并且其他的查询条件是空的时候，将数据存储缓存。
        if (reqVO.getPage() == 1 && StringUtils.isBlank(reqVO.getKeyword()) && reqVO.getPageSize() == 10) {
            setFirstPageGoodsCache(roomInfo.getIlId(), result);
        }
        return result;
    }

    @Override
    public GoodsPage<LiveGoodsConsoleUnBindListRspVO> getUnBindList(LiveGoodsConsoleUnBindListReqVO reqVO) {
        reqVO.setDefault();
        GoodsPage<LiveGoodsConsoleUnBindListRspVO> result;
        // 1、根据token获取用户信息。
        Token accountInfo = TokenThreadLocal.getToken();
        // 2、获取房间信息。
        RoomsEntityDTO roomInfo = roomInnerService.getRoomInfo(reqVO.getRoomId());
        if (roomInfo == null) {
            throw new BusinessException(BizErrorCode.EMPTY_ROOM);
        }
        // 3、获取绑定的商品id。
        LambdaQueryWrapper<LiveGoodsEntity> query = Wrappers.lambdaQuery();
        query.eq(LiveGoodsEntity::getIlId, roomInfo.getIlId());
        query.eq(LiveGoodsEntity::getGoodsStatus, GoodsConstant.GOODS_STATUS_ON);
        List<LiveGoodsEntity> liveGoodsEntities = liveGoodsMapper.selectList(query);
        List<Integer> bgIds = new ArrayList<>();
        if (liveGoodsEntities != null && !liveGoodsEntities.isEmpty()) {
            bgIds = liveGoodsEntities.stream().map(LiveGoodsEntity::getBgId).collect(Collectors.toList());
        }
        // 4、获取未绑定的商品id。
        Page<LiveGoodsConsoleUnBindListRspVO> page = new Page<>(reqVO.getPage(), reqVO.getPageSize());
        Map<String, Object> param = new HashMap<>(4);
        param.put("no_bg_id", bgIds);
//        param.put("account_id", accountInfo.getAccountId());
        param.put("goodsStatus", GoodsConstant.GOODS_STATUS_ON);
        param.put("keyWord", StringUtils.isBlank(reqVO.getKeyword()) ? "" : reqVO.getKeyword().trim());
        page = liveGoodsMapper.getUnBindList(page, param);
        result = new GoodsPage<>(reqVO.getPage(), reqVO.getPageSize(), (int) page.getTotal(), page.getRecords(), GoodsConstant.LIVE_GOODS_ENTRANCE_SWITCH_CLOSE);
        return result;
    }

    @Override
    public Boolean bindGoods(LiveGoodsConsoleBindGoodsReqVO reqVO) {
        // 1、简单做一个自我介绍。
        Token accountInfo = TokenThreadLocal.getToken();
        List<String> bgIds = Splitter.on(",").splitToList(reqVO.getBgIds());
        if (bgIds.isEmpty()) {
            return false;
        }
        // 2、获取房间信息。
        RoomsEntityDTO roomInfo = roomInnerService.getRoomInfo(reqVO.getRoomId());
        if (roomInfo == null) {
            throw new BusinessException(BizErrorCode.EMPTY_ROOM);
        }
        // 3、验证是否重复绑定。
        if (checkBindStatus(roomInfo.getIlId(), bgIds)) {
            throw new BusinessException(BizErrorCode.BIZ_REPEAT_BIND);
        }
        // 4、获取商品信息。
        LambdaQueryWrapper<GoodsEntity> queryGoods = Wrappers.lambdaQuery();
        queryGoods.in(GoodsEntity::getBgId, bgIds);
        queryGoods.eq(GoodsEntity::getGoodsStatus, GoodsConstant.GOODS_STATUS_ON);
        List<GoodsEntity> goods = goodsMapper.selectList(queryGoods);
        if (CollectionUtils.isEmpty(goods)) {
            throw new BusinessException(BizErrorCode.EMPTY_GOODS);
        }
        // 5、查询一下当前房间绑定的商品的最大的sort值。通过count来查询。（这里需要注意，必须保证库里的数据都是1开始。每次增1。）
        LambdaQueryWrapper<LiveGoodsEntity> queryLiveGoods = Wrappers.lambdaQuery();
        queryLiveGoods.eq(LiveGoodsEntity::getIlId, roomInfo.getIlId());
        queryLiveGoods.eq(LiveGoodsEntity::getGoodsStatus, GoodsConstant.GOODS_STATUS_ON);
        Integer count = liveGoodsMapper.selectCount(queryLiveGoods);
        // 5.5、校验如果超过极限值，报警。
        if (count + bgIds.size() > GoodsConstant.BIND_LIMIT) {
            throw new BusinessException(BizErrorCode.COMP_GOODS_BIND_LIMIT);
        }
        // 6、执行插入操作。
        List<LiveGoodsEntity> param = new ArrayList<>(goods.size());
        LiveGoodsEntity singleParam;
        LocalDateTime now = LocalDateTime.now();
        for (GoodsEntity single : goods) {
            singleParam = new LiveGoodsEntity();
            singleParam.setBgId(single.getBgId());
            singleParam.setIlId(roomInfo.getIlId());
            singleParam.setAccountId(accountInfo.getAccountId());
            singleParam.setGoodsStatus(GoodsConstant.GOODS_STATUS_ON);
            singleParam.setSort(++count);
            singleParam.setCreatedAt(now);
            singleParam.setUpdatedAt(now);
            param.add(singleParam);
        }
        // 7、删除缓存
        delFirstPageGoodsCache(roomInfo.getIlId());
        if (saveBatch(param)) {
            // 绑定成功后，触发刷新事件，若有直播中的进行刷新消息推送
            applicationEventPublisher.publishEvent(
                    new LiveGoodsListRefreshEvent(this, Collections.singletonList(roomInfo.getIlId()), "console绑定新商品"));


            roomStatusChange(roomInfo);


            return true;
        }
        return false;
    }

    private void roomStatusChange(RoomsEntityDTO roomInfo) {
        //只有正式直播才做状态重置
        if (Objects.equals(roomInfo.getLiveRormal(), 1)) {
            // 绑定成功之后，当前房间状态改为送审，需要点击【送审】按钮进行审核
            Integer auditStatus;
            String auditNote = null;
            if (RoomAuditWhichEnum.OPEN_ROOM_AUDIT.getStatus().equals(roomAuditWitch)) {
                auditStatus = RoomAuditStatusEnum.SUBMIT_FOR_APPROVAL.getAuditStatus();
                auditNote = "";
            } else {
                auditStatus = RoomAuditStatusEnum.APPROVED.getAuditStatus();
            }

            roomInnerService.updateByIl(RoomsEntityDTO.builder()
                    .auditStatus(auditStatus)
                    .auditNote(auditNote)
                    .updatedAt(LocalDateTime.now())
                    .ilId(roomInfo.getIlId()).build());
        }
    }

    /**
     * 设置审核状态
     */
    private Integer getAuditStatus() {
        //        开启房间审核时房间默认为送审
        return RoomAuditWhichEnum.OPEN_ROOM_AUDIT.getStatus().equals(roomAuditWitch)
                ? RoomAuditStatusEnum.SUBMIT_FOR_APPROVAL.getAuditStatus()
                : RoomAuditStatusEnum.APPROVED.getAuditStatus();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean unBindGoods(LiveGoodsConsoleUnBindGoodsReqVO reqVO) {
        // 1、根据参数查找绑定信息。
        LambdaQueryWrapper<LiveGoodsEntity> queryLiveGoods = Wrappers.lambdaQuery();
        queryLiveGoods.eq(LiveGoodsEntity::getBcgId, reqVO.getBcgId());
        LiveGoodsEntity bindInfo = liveGoodsMapper.selectOne(queryLiveGoods);
        if (bindInfo == null) {
            throw new BusinessException(BizErrorCode.EMPTY_GOODS);
        }
        // 2、获取count,查询一下当前房间绑定的商品的最大的sort值。通过count来查询。（这里需要注意，必须保证库里的数据都是1开始。每次增1。）
        LambdaQueryWrapper<LiveGoodsEntity> queryCount = Wrappers.lambdaQuery();
        queryCount.eq(LiveGoodsEntity::getIlId, bindInfo.getIlId());
        queryCount.eq(LiveGoodsEntity::getGoodsStatus, GoodsConstant.GOODS_STATUS_ON);
        Integer count = liveGoodsMapper.selectCount(queryCount);
        // 3、逻辑删除绑定信息。
        LambdaUpdateWrapper<LiveGoodsEntity> updateBind = Wrappers.lambdaUpdate();
        updateBind.set(LiveGoodsEntity::getGoodsStatus, GoodsConstant.GOODS_STATUS_OFF);
        updateBind.eq(LiveGoodsEntity::getBcgId, reqVO.getBcgId());
        int update = liveGoodsMapper.update(null, updateBind);
        if (update > 0) {
            delFirstPageGoodsCache(bindInfo.getIlId());
        }
        // 4、更新其他绑定信息的sort值。--比当前商品sort小的商品绑定数据不需要更新sort，比他大的减1.
        if (count > bindInfo.getSort()) {
            LambdaUpdateWrapper<LiveGoodsEntity> updateBatchBind = Wrappers.lambdaUpdate();
            updateBatchBind.eq(LiveGoodsEntity::getIlId, bindInfo.getIlId());
            updateBatchBind.eq(LiveGoodsEntity::getGoodsStatus, GoodsConstant.GOODS_STATUS_ON);
            updateBatchBind.between(LiveGoodsEntity::getSort, bindInfo.getSort() + 1, count + 1);
            updateBatchBind.setSql("sort = sort-1");
            liveGoodsMapper.update(null, updateBatchBind);
        }

        // 取消绑定后，触发刷新事件，若有直播中的进行刷新消息推送
        applicationEventPublisher
                .publishEvent(new LiveGoodsListRefreshEvent(this, Collections.singletonList(bindInfo.getIlId()), "console端取消绑定商品"));

        // 2、获取房间信息。
        RoomsEntityDTO roomInfo = roomInnerService.getRoomInfoByIlId(bindInfo.getIlId().toString());
        roomStatusChange(roomInfo);
        return update > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateSort(LiveGoodsConsoleUpdateSortGoodsReqVO reqVO) {
        Integer newSort = reqVO.getSort();
        // 1、获取数据库中该绑定信息的sort值。
        LambdaQueryWrapper<LiveGoodsEntity> queryLiveGoods = Wrappers.lambdaQuery();
        queryLiveGoods.eq(LiveGoodsEntity::getBcgId, reqVO.getBcgId());
        LiveGoodsEntity bindInfo = liveGoodsMapper.selectOne(queryLiveGoods);
        if (bindInfo == null) {
            throw new BusinessException(BizErrorCode.EMPTY_GOODS);
        }
        Integer oldSort = bindInfo.getSort();
        if (oldSort.equals(newSort)) {
            throw new BusinessException(BizErrorCode.BIZ_REPEAT_SERIAL_NUMBER);
        }
        // 2、获取count.
        LambdaQueryWrapper<LiveGoodsEntity> queryCount = Wrappers.lambdaQuery();
        queryCount.eq(LiveGoodsEntity::getIlId, bindInfo.getIlId());
        queryCount.eq(LiveGoodsEntity::getGoodsStatus, GoodsConstant.GOODS_STATUS_ON);
        Integer count = liveGoodsMapper.selectCount(queryCount);
        if (newSort > count) {
            throw new BusinessException(BizErrorCode.COMP_GOODS_SERIAL_NUMBER_INVALID);
        }
        // 2.5、删除绑定商品列表第一页数据。
        delFirstPageGoodsCache(bindInfo.getIlId());
        // 3、执行更新操作。分为两步，第一步：将新老两个值之间的数据修改。然后就是修改当前绑定信息。
        // 大变小，中间值增大1。小变大，中间值减1。
        LambdaUpdateWrapper<LiveGoodsEntity> updateBatchBind = Wrappers.lambdaUpdate();
        updateBatchBind.eq(LiveGoodsEntity::getIlId, bindInfo.getIlId());
        updateBatchBind.eq(LiveGoodsEntity::getGoodsStatus, GoodsConstant.GOODS_STATUS_ON);
        if (newSort > oldSort) {
            updateBatchBind.between(LiveGoodsEntity::getSort, oldSort, newSort);
            updateBatchBind.setSql("sort = sort-1");
        } else {
            updateBatchBind.between(LiveGoodsEntity::getSort, newSort, oldSort);
            updateBatchBind.setSql("sort = sort+1");
        }
        liveGoodsMapper.update(null, updateBatchBind);
        // 更新当前数据的sort.
        LambdaUpdateWrapper<LiveGoodsEntity> updateCurrent = Wrappers.lambdaUpdate();
        updateCurrent.eq(LiveGoodsEntity::getBcgId, reqVO.getBcgId());
        updateCurrent.set(LiveGoodsEntity::getSort, newSort);
        liveGoodsMapper.update(null, updateCurrent);

        // 更改序号后，触发刷新事件，若有直播中的进行刷新消息推送
        applicationEventPublisher
                .publishEvent(new LiveGoodsListRefreshEvent(this, Collections.singletonList(bindInfo.getIlId()), "console端变更序号"));
        return true;
    }

    /**
     * 验证房间和商品是否是重复绑定的。
     *
     * @param ilId  房间id
     * @param bgIds 商品id集合
     * @return true表示重复绑定过。false表示没有。
     */
    private boolean checkBindStatus(Integer ilId, List<String> bgIds) {
        // 校验逻辑
        LambdaQueryWrapper<LiveGoodsEntity> query = Wrappers.lambdaQuery();
        query.eq(LiveGoodsEntity::getIlId, ilId).in(LiveGoodsEntity::getBgId, bgIds)
                .eq(LiveGoodsEntity::getGoodsStatus, GoodsConstant.GOODS_STATUS_ON);
        Integer count = liveGoodsMapper.selectCount(query);
        return count > 0;
    }

    /**
     * 获取缓存数据----与房间绑定的商品信息（第一页，每页10个）
     *
     * @param ilId
     * @return
     */
    private GoodsPage<LiveGoodsConsoleBindListRspVO> getFirstPageGoodsCache(Integer ilId) {
        String cacheValue = stringRedisTemplate.opsForValue().get(GoodsConstant.FIRST_PAGE_LIVE_GOODS_KEY + ilId);
        if (StringUtils.isNotEmpty(cacheValue)) {
            GoodsPage goodsPage = JsonUtil.objectFromJSONString(cacheValue, GoodsPage.class);
            if (Objects.nonNull(goodsPage) && CollectionUtils.isNotEmpty(goodsPage.getData())) {
                goodsPage.setData(JsonUtil.arrayFromJSONString(JsonUtil.toJsonString(goodsPage.getData()), LiveGoodsConsoleBindListRspVO.class));
            }
            return goodsPage;
        }
        return null;
    }

    /**
     * 将数据存入缓存----与房间绑定的商品信息（第一页，每页10个）
     *
     * @param ilId
     * @return
     */
    private void setFirstPageGoodsCache(Integer ilId, GoodsPage<LiveGoodsConsoleBindListRspVO> page) {
        stringRedisTemplate.opsForValue().set(GoodsConstant.FIRST_PAGE_LIVE_GOODS_KEY + ilId, JsonUtil.toJsonString(page),
                GoodsConstant.FIRST_PAGE_LIVE_GOODS_KEY_EXPIRE, TimeUnit.SECONDS);
    }

    /**
     * 将数据从缓存删除----与房间绑定的商品信息（第一页，每页10个）
     *
     * @param ilId
     * @return
     */
    @Override
    public void delFirstPageGoodsCache(Integer ilId) {
        stringRedisTemplate.delete(GoodsConstant.FIRST_PAGE_LIVE_GOODS_KEY + ilId);
    }

    @Override
    public PageVO<GetGoodsInfoResponseVO> getGuoxinPrdBindList(GuoxinPrdApiBindReqVO reqVO) {
        String roomId = reqVO.getRoomId();
        RoomsEntityDTO roomInfo = Optional.ofNullable(roomInnerService.getRoomInfo(roomId)).orElseThrow(() -> new BusinessException(BizErrorCode.EMPTY_ROOM));
        Integer ilId = roomInfo.getIlId();
//        使用房间 id 获取和房间关联的产品信息-产品编号,产品类型
        LambdaQueryWrapper<RoomGoodsEntity> queryLiveGoods = Wrappers.lambdaQuery();
        queryLiveGoods.eq(RoomGoodsEntity::getIlId, ilId);
        queryLiveGoods.eq(RoomGoodsEntity::getIsDeleted, 0);
        queryLiveGoods.orderByDesc(RoomGoodsEntity::getPrdType);
        Page<RoomGoodsEntity> page = new Page(reqVO.getPage(), reqVO.getPageSize());
        page = roomGoodsMapper.selectPage(page, queryLiveGoods);
        int goodSwitch = 0;
        List<GetGoodsInfoResponseVO> goodsInfoList = new ArrayList<>();
        List<RoomGoodsEntity> records = page.getRecords();
        Map<String, Object> tool = redisTemplate.opsForHash().entries(RedisKey.INTERACT_TOOL + roomId);

        if (CollUtil.isNotEmpty(records)) {
            //        将产品信息拼接成目标参数,传递给国信
            GetGoodsInfoRequestVO dto = new GetGoodsInfoRequestVO();
            List<String> list = new ArrayList<>();
            for (RoomGoodsEntity roomGoodsEntity : records) {
                StringBuilder sb = new StringBuilder();
                sb.append(roomGoodsEntity.getPrdType()).append(".").append(roomGoodsEntity.getPrdCode());
                list.add(sb.toString());
            }
            String prdCodes = String.join("|", list);
            dto.setPrdCodes(prdCodes);
            dto.setIlId(ilId);
            dto.setShareid(reqVO.getShareid());
            goodsInfoList = Optional.ofNullable(guoxinPrdService.getGoodsInfoList(dto)).orElse(new ArrayList<>());

            if (tool.containsKey(GoodsConstant.LIVE_GOODS_ENTRANCE_SWITCH_KEY)) {
                goodSwitch = Integer.parseInt(String.valueOf(tool.get(GoodsConstant.LIVE_GOODS_ENTRANCE_SWITCH_KEY)));
            }else {
                goodSwitch = goodsInfoList.size() > 0 ? 1 : 0;
                redisTemplate.opsForHash().put(RedisKey.INTERACT_TOOL + reqVO.getRoomId(), GoodsConstant.LIVE_GOODS_ENTRANCE_SWITCH_KEY, goodSwitch);
            }
            goodsInfoList.sort(Comparator.comparing(GetGoodsInfoResponseVO::getPrdType).reversed());
        }else {
            if (tool.containsKey(GoodsConstant.LIVE_GOODS_ENTRANCE_SWITCH_KEY)) {
                goodSwitch = Integer.parseInt(String.valueOf(tool.get(GoodsConstant.LIVE_GOODS_ENTRANCE_SWITCH_KEY)));
            }
        }
//        获取到产品信息,拼接后返回给前端
        return new PageVO<>(reqVO.getPage(), (int) page.getSize(), (int) page.getTotal(), goodsInfoList, goodSwitch);
    }

    private String getLiveGoodsPrdCodes(List<RoomGoodsEntity> liveGoodsEntities) {
//        @todo 目前为伪造数据,仅供测试使用,数据结构为:国信的 产品类型.产品编号|产品类型.产品编号
        return thirdPartyProperties.getProd().getCodes();
    }


    /**
     * 获取观众端商品入口开关状态。
     *
     * @param roomId
     * @return
     */
    private Integer getGoodsSwitchCache(String roomId, Integer hasGoods) {
        if (StringUtils.isBlank(roomId)) {
            return 0;
        }
        Object cacheObj = redisTemplate.opsForHash().get(RedisKey.INTERACT_TOOL + roomId, GoodsConstant.LIVE_GOODS_ENTRANCE_SWITCH_KEY);
        return Objects.nonNull(cacheObj) ? (Integer) cacheObj : (hasGoods == 1 ? 1 : 0);
    }

}
